package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderDTO;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id查询预约信息
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        Order order = orderService.findById(id);

        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, order);
    }

    /**
     * 体检预约
     * @param orderDTO
     * @return
     */
    @PostMapping("/submitOrder")
    public Result submitOrder(@RequestBody OrderDTO orderDTO){
        // 校验预定验证码的合法性
        Integer validateCode = (Integer) redisTemplate.opsForValue()
                .get(RedisMessageConstant.SENDTYPE_ORDER + "_" + orderDTO.getTelephone());
        if (validateCode == null ||
                Integer.compare(Integer.valueOf(orderDTO.getValidateCode()), validateCode) != 0){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Integer recordCount = orderService.submitOrder(orderDTO);

        return new Result(true, MessageConstant.ORDER_SUCCESS, recordCount);
    }
}
